import os.path
# -*- coding: utf-8 -*-
__author__      = "Damien Lebrun"
__date__        = "$23-Nov-2008 12:43:58$"
__revision__    = "$Id: creator.py 372 2008-12-03 10:51:36Z dinoboff $"

from common import UtilsError, Command, create_file
import os
import settings

class CreatorError(UtilsError): pass

class Creator(Command):
	FILES = {
		'default.php': settings.TEMPLATE_DEFAULT,
		'.htaccess': settings.TEMPLATE_HTACCESS_ROOT,
		'readme.rst': settings.TEMPLATE_READ_ME,
		'build.py': settings.TEMPLATE_BUILD,
		'assets/.htaccess': settings.TEMPLATE_HTACCESS_ASSETS,
		'library/functions.php': settings.TEMPLATE_FUNCTION
	}
	DIRS = (
		'assets',
		'theme',
		'library')

	def __init__(self, name, dist_name=None, *args, **kwargs):
		kwargs['logger_name'] = 'vanillafriends.creator'
		super(Creator, self).__init__(*args, **kwargs)
		self.name = name
		self.dist_name = dist_name or self._normalize_name(self.name)
		if not self.dist_name:
			raise CreatorError(
				'Won\'t be able to create the extension.'
				'Set "dist_name" (extension directory and package name.')
		self.details = {'EXT_NAME': name, 'EXT_DIST_NAME': self.dist_name}

	def create(self):
		base_dir = os.path.join(self.base_dir, self.dist_name)
		if os.path.exists(base_dir):
			self.log.fatal(
				'An extension with the same name already exist in "%s"',
				self.base_dir)
			raise CreatorError("The extension directory already exist.")
		
		for dir_path in self.DIRS:
			self.log.info('Creating directory "%s"...', dir_path)
			os.makedirs(os.path.join(base_dir, dir_path))

		for file_path in self.FILES.keys():
			self.log.info('Creating "%s"...', file_path)
			create_file(
				file_path, self.FILES[file_path] % self.details, base_dir)


